﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using CloudPms.Common.CacheProvider;
using CloudPms.Common.Utils;

namespace CloudPms.Domain.Repository
{
    public class StatusVerifyPolicy
    {
        private static volatile IList<KeyValuePair<RoomStatus, RoomStatus>> _policies;

        private static volatile StatusVerifyPolicy _instance;

        private static readonly object syncRoot = new object();

        private StatusVerifyPolicy()
        {
        }

        public static StatusVerifyPolicy Instance
        {
            get
            {
                if(_instance==null)
                {
                    lock(syncRoot)
                    {
                        if(_instance==null)
                        {
                            var svp = new StatusVerifyPolicy();

                            svp.InitPolicies();

                            _instance = svp;

                        }
                    }
                }
                return _instance;
            }
        }

        public bool ValidateTransferStatus(RoomStatus origin,RoomStatus destination)
        {
            return Policies.Contains(new KeyValuePair<RoomStatus, RoomStatus>(origin, destination));
        }

        public IList<KeyValuePair<RoomStatus, RoomStatus>> Policies
        {
            get
            {
                if (_policies == null)
                {
                    lock (syncRoot)
                    {
                        if (_policies == null)
                        {
                            InitPolicies();
                        }
                    }
                }
                return _policies;
            }
        }

        private void InitPolicies()
        {
            _policies = new List<KeyValuePair<RoomStatus, RoomStatus>>();

            XmlDocument doc = new XmlDocument();

            string path = DbContextService.GetRootPath() + @"StatusVerifyPolicy.xml";

            doc.Load(path);

            XmlNodeList nodes = doc.SelectNodes("/StatusPolicy/policy");

            _policies = (from XmlNode node in nodes
                           select new KeyValuePair<RoomStatus, RoomStatus>(
                               EnumHelper.GetValue<RoomStatus>(node.Attributes["orign"].Value),
                               EnumHelper.GetValue<RoomStatus>(node.Attributes["dest"].Value))).ToList();

        }
    }
}
